#By Daoyu 2010-07-10
from django.shortcuts import render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.template import RequestContext
from django.db.models import Q
from django.contrib.auth.models import User

import os

from uncle.project.models import *
from uncle.util.page import *
from uncle.util.util import *
from uncle.users.models import *
from uncle.util.util import match_email_address

#===============================================================================
# 
#===============================================================================
def get_artist_video(request, p_id, artist_id):
    videos = video.objects.filter(user__id=artist_id)
    return render_to_response('project/set_artist_video.html',
            {'videos':videos, 'project_id':p_id, 'artist_id':artist_id, },
            context_instance=RequestContext(request))

def set_artist_project_video(request, p_id, art_id):
    pa = Project_artist.objects.filter(project__id=p_id).filter(artist__id=art_id)[0]
    
    if request.GET.has_key('movie'):
        pa.video = request.GET['movie']
    
    pa.save()
    return HttpResponseRedirect('/project/' + str(p_id) + '/edit/')

#===============================================================================
# By Ruilin
#===============================================================================
def get_basket_video(request, p_id, b_id):
    videos = None
    bvs = Basket_video.objects.filter(basket__id=b_id) 
    for bv in bvs:
        videos += Video.objects.filter(video__id=bv.video.id)
    return render_to_response('project/import_basket_video.html',
            {'videos':videos, 'project_id':p_id, 'basket_id':artist_id, },
            context_instance=RequestContext(request))

def set_basket_project_video(request, p_id, b_id):
    pa = Project_artist.objects.filter(project__id=p_id).filter(artist__id=art_id)[0]
    
    if request.GET.has_key('movie'):
        pa.video = request.GET['movie']
    
    pa.save()
    return HttpResponseRedirect('/project/' + str(p_id) + '/edit/')
    

#-------------------------------------------------------------------------------
# New a project.
#-------------------------------------------------------------------------------
@login_required
def new_project(request):
    if request.method == 'GET':
        clients = User.objects.filter(Q(user_permissions__codename='is_client'))

        files = range(0, 3)

        return render_to_response('project/new.html',
            { 'files':files, 'clients':clients},
            context_instance=RequestContext(request))
    elif request.method == 'POST':
        obj = Project()
        obj.name = request.POST['p_name']
        obj.brand = request.POST['p_brand']
        obj.city = request.POST['p_city']
        obj.creator = request.user
      
        #if request.POST.has_key('client_id'):
        if request.POST['client'] != '':
            obj.client = User.objects.get(id=request.POST['client'])
            
        else:
            u_n = request.POST['username']
            company = request.POST['company']
            pwd = request.POST['pwd']
            email = request.POST['email']
            if not match_email_address(email):
                email = ''
            
            if request.POST['username']=='':
                request.user.message_set.create(message='Please select a client or create a new one.')
                return HttpResponseRedirect('/project/new/')
            elif User.objects.filter(username=request.POST['username']):
                request.user.message_set.create(message='User name already exists.')
                return HttpResponseRedirect('/project/new/')
                
            user = User()
            user.username = u_n
            user.set_password(pwd)
            user.save()
        
            
            user.email = email
            user.user_permissions.add(Permission.objects.get(codename='is_client'))
            user.save()
            
            up = User_profile()
            up.user = user
            up.company = company
            up.save()
            
            obj.client = user            
            
        obj.description = request.POST['description']
        obj.save()

        for a_id in request.POST.getlist('artists'): # add artist to the project.`            
            art = User.objects.filter(id=a_id)
            if art:
                pa = Project_artist()
                pa.project = obj
                pa.artist = art[0]
                pa.save()
                
                es = Email_sta.objects.filter(user__id=a_id)
                if es:
                    es[0].project_counts = es[0].project_counts + 1
                    es[0].save()
                #update_pv(obj, bv[0])
        
        for youtube in request.POST.getlist('moods'):
            pt = Project_youtube()
            pt.youtube_text = youtube_text          # Kalle: text field added
            pt.youtube_title = youtube_title          # Kalle: text field added            
            pt.show = show 
            pt.youtube = youtube
            pt.project = obj
            pt.save()

        for i in range(0, 5): # save the description files.Kalle: changed 3 to 5
            if request.FILES.has_key('file' + str(i)):
                pf = Project_file()
                pf.project = obj

                f_type = request.FILES['file' + str(i)].name.encode('utf-8')
                from uncle.util.file import upload

                if is_video(f_type):
                    _f_name = upload('upload/project/' + str(obj.id),
                                 request.FILES['file' + str(i)],
                                 pre='/var/www/uncle/',
                                 type='.mp4')

                    f_name = _f_name.split('.')[0]

                    os.system('/usr/local/bin/ffmpeg -i /var/www/uncle/' + _f_name
                              + ' -vcodec libx264 -vpre slow -vpre ipod640 -s 480x360 /var/www/uncle/'
                              + f_name + '.mp4')
                    os.system('/usr/local/bin/ffmpeg -i /var/www/uncle/' + _f_name + 
                            ' /var/www/uncle/' + f_name + '.jpg')
                    os.system('rm /var/www/uncle/' + _f_name)
                    pf.file = f_name + '.mp4'

                    update_pv(obj, pf.file)
                elif is_picture(f_type):
                    pf.file = upload('upload/project/' + str(obj.id),
                                 request.FILES['file' + str(i)],
                                 pre='/var/www/uncle/')

                if request.POST.has_key('desc' + str(i)): # for each text description of the file.
                        pf.text = request.POST['desc' + str(i)]
                pf.save()

        request.user.message_set.create(message='New project created.')
        return HttpResponseRedirect('/project/' + str(obj.id) + '/')

#-------------------------------------------------------------------------------
# Show all the projects.
#-------------------------------------------------------------------------------
@login_required
def all_project(request):
    if not request.user.has_perm('users.is_producer'):
        return HttpResponseRedirect('/403/?msg=You do not have permission to view this page')
    if request.method == 'GET':
        projects = Project.objects.all()
        _projects = split_into_pages(request, projects)

        return render_to_response('project/all.html',
            {'projects':_projects, },
            context_instance=RequestContext(request))

#-------------------------------------------------------------------------------
# Show detail of a project.
#-------------------------------------------------------------------------------
#@login_required
#def detail(request, p_id):
#    obj = Project.objects.filter(id=p_id)
#    clients = User.objects.filter(Q(user_permissions__codename='is_client'))
#    if not obj:
#        return HttpResponseRedirect('/403/?msg=Project does not exist!')
#    
#    pces = Project_client_email.objects.filter(project__id=p_id)
#
#    pas = split_into_lists(
#        [x for x in Project_artist.objects.filter(project__id=p_id)], count=6)
#    pys = split_into_lists(
#        [x for x in Project_youtube.objects.filter(project__id=p_id, show__exact=True)], count=6)
#    pfs = split_into_lists(Project_file.objects.filter(project__id=p_id, show__exact=True), count=6)
#    pces = Project_client_email.objects.filter(project__id=p_id)
##    up = User_profile.objects.filter(user__id = 'is_client')
#    
#
#    pv = None  # the current project's playing film.
#    if request.GET.has_key('m'):
#        pf = Project_file.objects.filter(id=request.GET['m'])
#        if pf:
#            pv = pf[0].file
#    elif request.GET.has_key('a'):
#        pv = request.GET['a']
#    else:
#        _pv = Project_video.objects.filter(project__id=p_id)
#        if _pv:
#            pv = _pv[0].film
#
#    return render_to_response('project/detail.html',
#        {'project':obj[0], 'pass':pas, 'pfss':pfs,
#         'pv':pv, 'pys':pys, 'pces':pces, 'client_detail':clients[0], },
#        context_instance=RequestContext(request))

@login_required
def detail(request, p_id):
    obj = Project.objects.filter(id=p_id)
    clients = User.objects.filter(Q(user_permissions__codename='is_client'))
    if not obj:
        return HttpResponseRedirect('/403/?msg=Project does not exist!')
    
    pces = Project_client_email.objects.filter(project__id=p_id)

    pas = split_into_lists(
        [x for x in Project_artist.objects.filter(project__id=p_id).exclude(artist__username='Moods')], count=6)
    pys = split_into_lists(
        [x for x in Project_youtube.objects.filter(project__id=p_id, show__exact=True)], count=6)
    pfs = split_into_lists(Project_file.objects.filter(project__id=p_id, show__exact=True), count=6)
    pces = Project_client_email.objects.filter(project__id=p_id)
    moods = split_into_lists([x for x in Project_artist.objects.filter(project__id=p_id).filter(artist__username='Moods')], count=6)
    attachments = Project_file.objects.filter(project__id=p_id).filter(file__endswith='.txt')    #show attachments: only .txt file
#    up = User_profile.objects.filter(user__id = 'is_client')
  

    pv = None  # the current project's playing film.
    if request.GET.has_key('m'):
        pf = Project_file.objects.filter(id=request.GET['m'])
        if pf:
            pv = pf[0].file
    elif request.GET.has_key('a'):
        pv = request.GET['a']
    else:
        _pv = Project_video.objects.filter(project__id=p_id)
        if _pv:
            pv = _pv[0].film

    return render_to_response('project/detail.html',
        {'project':obj[0], 'pass':pas, 'pfss':pfs,
         'pv':pv, 'pys':pys, 'pces':pces, 'client_detail':clients[0],
         'moods':moods, 'attachments':attachments, },
        context_instance=RequestContext(request))

#-------------------------------------------------------------------------------
# Edit the description of a project.
#-------------------------------------------------------------------------------
@login_required
def edit(request, p_id):
    
    obj = Project.objects.filter(id=p_id)
    if not obj:
        return HttpResponseRedirect('/403/?msg=Project does not exist!')

    pys = split_into_lists(
        [x for x in Project_youtube.objects.filter(project__id=p_id)], count=6) # Kalle: 2 changed to 6
    artists = User.objects.filter(Q(user_permissions__codename='is_artist'))

    pas = split_into_lists(
        [x for x in Project_artist.objects.filter(project__id=p_id)])
    pfs = split_into_lists(Project_file.objects.filter(project__id=p_id))
    pces = Project_client_email.objects.filter(project__id=p_id)
    bas = Basket.objects.filter(user__id=request.user.id)
    
    pv = None  # the current project's playing film.    
    if request.method == 'GET':
        
        if request.GET.has_key('m'):
            pf = Project_file.objects.filter(id=request.GET['m'])
            if pf:
                pv = pf[0].file
        elif request.GET.has_key('a'):
            pv = request.GET['a']
        else:
            _pv = Project_video.objects.filter(project__id=p_id)
            if _pv:
                pv = _pv[0].film

       
    elif request.method == 'POST':
        pass
    return render_to_response('project/detail_edit.html',
            {'project':obj[0], 'pass':pas, 'pfss':pfs, 'pces':pces,
             'artists':artists, 'pys':pys, 'pv':pv, 'bas':bas},
            context_instance=RequestContext(request))

#-------------------------------------------------------------------------------
# Save the changes to the project's description.
#-------------------------------------------------------------------------------
@login_required
def save(request, p_id):
    if not request.user.has_perm('users.is_producer'):
        return HttpResponseRedirect('/403/?msg=You do not have permission to view this page')
    if request.method == 'POST':
        obj = Project.objects.filter(id=p_id)
        if not obj:
            return HttpResponseRedirect('/403/?msg=Project does not exist!')

        obj[0].description = request.POST['description']

        obj[0].save()
        request.user.message_set.create(
            message='Description updated.')

        return HttpResponseRedirect('/project/' + str(obj[0].id) + '/edit/')

#-------------------------------------------------------------------------------
# Delete the project with id = p_id
#-------------------------------------------------------------------------------
@login_required
def delete(request, p_id):
    if request.user.username == 'kth' or Project.objects.get(id=p_id).creator.id == request.user.id:
        Project.objects.filter(id=p_id).delete()

        request.user.message_set.create(
            message='Project deleted.')

    return HttpResponseRedirect('/project/all/')

#-------------------------------------------------------------------------------
# Delete an attached file from project detail page.
#-------------------------------------------------------------------------------
@login_required
def delete_file(request, p_id, f_id):
    if request.user.username == 'kth' or Project.objects.get(id=p_id).creator.id == request.user.id:
        Project_file.objects.filter(id=f_id).filter(project__id=p_id).delete()
       # Project_video.objects.filter(id = f_id).filter(project__id = p_id).delete() # Kalle: Created

        request.user.message_set.create(
            message='Attachment deleted.')

    return HttpResponseRedirect('/project/' + str(p_id) + '/edit/')

#-------------------------------------------------------------------------------
# Hide an attached file from project detail page.
#-------------------------------------------------------------------------------
@login_required
def hide_file(request, p_id, f_id):
    if request.user.username == 'kth' or Project.objects.get(id=p_id).creator.id == request.user.id:
       pf = Project_file.objects.filter(id=f_id).filter(project__id=p_id)[0]
       pf.show = False
       
       pf.save()

       request.user.message_set.create(
            message='Attachment updated.')

    return HttpResponseRedirect('/project/' + str(p_id) + '/edit/')

#-------------------------------------------------------------------------------
# Show an attached file from project detail page.
#-------------------------------------------------------------------------------
@login_required
def show_file(request, p_id, f_id):
    if request.user.username == 'kth' or Project.objects.get(id=p_id).creator.id == request.user.id:
        pf = Project_file.objects.filter(id=f_id).filter(project__id=p_id)[0]
        pf.show = True
        
        pf.save()

        request.user.message_set.create(
            message='Attachment deleted.')

    return HttpResponseRedirect('/project/' + str(p_id) + '/edit/')

#-------------------------------------------------------------------------------
# Update a project's main video.
#-------------------------------------------------------------------------------
def update_pv(project, file):
    _pv = Project_video.objects.filter(project__id=project.id)
    if _pv:
        _pv[0].film = file
        _pv[0].save()
    else:
        pv = Project_video()
        pv.project = project
        pv.film = file
        pv.save()

#-------------------------------------------------------------------------------
# Add attachment at project detail page.
#-------------------------------------------------------------------------------
@login_required
def add_file(request, p_id):
    if request.method == 'POST':
        obj = Project.objects.filter(id=p_id)
        if obj:
            pf = Project_file()
            pf.project = obj[0]
            
            f_type = request.FILES['new_file'].name.encode('utf-8')
            from uncle.util.file import upload
            
            if is_video(f_type):
                _f_name = upload('upload/project/' + p_id,
                                 request.FILES['new_file'],
                                 pre='/var/www/uncle/',
                                 type='.mp4')

                f_name = _f_name.split('.')[0]
    
                os.system('/usr/local/bin/ffmpeg -i /var/www/uncle/' + _f_name
                          + ' -vcodec libx264 -vpre slow -vpre ipod640 -s 480x360 /var/www/uncle/'
                          + f_name + '.mp4')
    
                os.system('/usr/local/bin/ffmpeg -i /var/www/uncle/' + _f_name + 
                        ' /var/www/uncle/' + f_name + '.jpg')
    
                os.system('rm /var/www/uncle/' + _f_name)
                pf.file = f_name + '.mp4'
                update_pv(obj[0], pf.file)    
                
                # save as moods video, by Ruilin
                vi = video()
                
                from uncle.util.file import upload
                _f_name = upload('upload/video/' + str(request.user.id),
                                 request.FILES['new_file'],
                                 pre = '/var/www/uncle/',
                                 type = '.mp4')
    
                f_name = _f_name.split('.')[0]
    
   
                os.system('/usr/local/bin/ffmpeg -i /var/www/uncle/' + _f_name
                          + ' -vcodec libx264 -vpre slow -vpre ipod640 -s 480x360 /var/www/uncle/'
                          + f_name + '.mp4')
    
                os.system('/usr/local/bin/ffmpeg -i /var/www/uncle/' + _f_name +
                        ' /var/www/uncle/' + f_name + '.jpg')
    
                os.system('rm /var/www/uncle/' + _f_name)
    
                
                vi.user = User.objects.get(username='moods')
                vi.movie = f_name + '.mp4'
                vi.text = request.POST['txt']
                vi.title = request.POST['title']
                
                vi.save()            
            elif is_picture(f_type):
                pf.file = upload('upload/project/' + p_id,
                                 request.FILES['new_file'],
                                 pre='/var/www/uncle/')            

            if request.POST.has_key('txt'): # for each text description of the file.
                pf.text = request.POST['txt']

            if request.POST.has_key('title'): # Kalle: for file title
                pf.title = request.POST['title']    

            if request.POST.has_key('file_show'): # Kalle: for file title
                pf.show = request.POST['file_show']   


            pf.save()

            request.user.message_set.create(
                message='Attachment added.')
    return HttpResponseRedirect('/project/' + str(p_id) + '/edit/')

#-------------------------------------------------------------------------------
# Delete artist from project detail page.
#-------------------------------------------------------------------------------
@login_required
def delete_artist(request, p_id, a_id):
    if request.user.username == 'kth' or Project.objects.get(id=p_id).creator.id == request.user.id:
        obj = Project_artist.objects.filter(id=a_id).filter(project__id=p_id)
        if obj:
            #-------- The artist's project counts ++
            es = Email_sta.objects.filter(user__id=obj[0].artist.id)
            if es and es[0].project_counts > 0 :
                es[0].project_counts = es[0].project_counts - 1
                es[0].save()
            #--------

            obj[0].delete()

            request.user.message_set.create(
                message='Artist deleted.')

    return HttpResponseRedirect('/project/' + str(p_id) + '/edit/')

#-------------------------------------------------------------------------------
# Add artist at project detail page.
#-------------------------------------------------------------------------------
@login_required
def add_artist(request, p_id):
    if request.method == 'POST' and (request.user.username == 'kth' or Project.objects.get(id=p_id).creator.id == request.user.id):
        pas = Project_artist.objects.filter(project__id=p_id).filter(artist__id=request.POST['new_user'])

        if not pas:
            obj = Project.objects.filter(id=p_id)
            if obj :
                art = User.objects.filter(id=request.POST['new_user'])
                if art:
                    #-------- The artist's project counts ++
                    es = Email_sta.objects.filter(user__id=art[0].id)
                    if es:
                        es[0].project_counts = es[0].project_counts + 1
                        es[0].save()
                    #--------

                    pa = Project_artist()
                    pa.project = obj[0]
                    pa.artist = art[0]

                    pa.save()
                    request.user.message_set.create(message='Attachment added.')
        else:
            request.user.message_set.create(message='User already exists!')
    return HttpResponseRedirect('/project/' + str(p_id) + '/edit/')

#-------------------------------------------------------------------------------
# Delete the chosen youtube URL from the project edit page.
#-------------------------------------------------------------------------------
def delete_youtube(request, p_id, y_id):
    if request.user.username == 'kth' or Project.objects.get(id=p_id).creator.id == request.user.id:
        Project_youtube.objects.filter(project__id=p_id).filter(id=y_id).delete()

        request.user.message_set.create(message='Youtube URL deleted.')

    return HttpResponseRedirect('/project/' + str(p_id) + '/edit/')

#-------------------------------------------------------------------------------
# show the youtube video.
#-------------------------------------------------------------------------------
def show_youtube(request, p_id, y_id):
    if request.user.username == 'kth' or Project.objects.get(id=p_id).creator.id == request.user.id:
        py = Project_youtube.objects.filter(project__id=p_id).filter(id=y_id)[0]
        py.show = True
        py.save()

        request.user.message_set.create(message='Youtube URL displayed.')

    return HttpResponseRedirect('/project/' + str(p_id) + '/edit/')

#-------------------------------------------------------------------------------
# hide the youtube video.
#-------------------------------------------------------------------------------
def hide_youtube(request, p_id, y_id):
    if request.user.username == 'kth' or Project.objects.get(id=p_id).creator.id == request.user.id:
        py = Project_youtube.objects.filter(project__id=p_id).filter(id=y_id)[0]
        py.show = False
        py.save()

        request.user.message_set.create(message='Youtube URL hided.')

    return HttpResponseRedirect('/project/' + str(p_id) + '/edit/')

#-------------------------------------------------------------------------------
# Add a new youtube URL to project.
#-------------------------------------------------------------------------------
def add_youtube(request, p_id):
    if request.method == 'POST':
        obj = Project.objects.filter(id=p_id)
        if obj:
            youtube = request.POST['new_youtube']
            youtube_text = request.POST['you_text']      # Kalle: text-field added
            youtube_title = request.POST['you_title']
            show = request.POST['youtube_show']      # Kalle: Show-field
            youtube = youtube.split('&')[0]
            youtube = youtube.split('v=')[-1]



    #        if request.POST.has_key('you_txt'): # for each text description of the file.
    #            py.text = request.POST['you_txt']


            

            py = Project_youtube()
            py.youtube = youtube
            py.youtube_title = youtube_title                      # Kalle: text-field added
            py.youtube_text = youtube_text 
            py.show = show  
            py.project = obj[0]
            
            # By Ruilin: add youtube as a video
            vi = video()
            vi.user = User.objects.get(username="moods")
            vi.title = youtube_title
            vi.text = youtube_text
            vi.movie = youtube
            vi.save()

            py.save()
            request.user.message_set.create(message='Youtube URL added.')

    return HttpResponseRedirect('/project/' + str(p_id) + '/edit/')

#-------------------------------------------------------------------------------
# Change the project's name
#-------------------------------------------------------------------------------
def change_project_name(request, p_id):
    if request.method == 'POST':
        project = Project.objects.filter(id=p_id)
        if project:
            project[0].name = request.POST['project_name']
            project[0].brand = request.POST['project_brand']
            project[0].city = request.POST['project_city']
            project[0].save()
            
            request.user.message_set.create(message='Project name updated')
    return HttpResponseRedirect('/project/' + str(p_id) + '/edit/')

#-------------------------------------------------------------------------------
# Change visible youtube links - by Kalle
#-------------------------------------------------------------------------------
#def change_youtube(request, p_id):
#    if obj:
#        
#            obj.show = request.POST['youtube_show']
#            obj.save()  



#            if obj:
#                obj = Project_youtube.objects.filter(id = p_id)
#                obj[0].show = request.POST['youtube_show']
#                obj[0].save()
        
#            show = request.POST['youtube_show']
#
#            py = Project_youtube()
#            py.show = show
#            py.project = obj[0]
#            py.save()


#            show = request.POST['youtube_show']      # Kalle: Show-field

#            py = Project_youtube()
#            py.show = show  
#            py.project = obj[0]

#            py.save()


# u_e = User_expire.objects.get(user__id=request.POST['c_u_id'])
#            if request.POST['exp_start'] and request.POST['exp_end']:                
#                u_e.start = request.POST['exp_start'] 
#                u_e.end = request.POST['exp_end']
#
#            else:
#                u_e.start = None
#                u_e.end = None
#            try:
#                u_e.save()   



            
#            request.user.message_set.create(message = 'Youtube clips refreshed.')

#    return HttpResponseRedirect('/project/' + str(p_id) + '/edit/')


#-------------------------------------------------------------------------------
#  Add client's email to project.
#-------------------------------------------------------------------------------
def add_client_email(request, p_id):
    
    if request.method == 'POST':
        project = Project.objects.filter(id=p_id)
        if project:
            email = request.POST['client_email']
            name = request.POST['client_name']           # Kalle: name-field added
            title = request.POST['client_title']         # Kalle: title-field added
            if match_email_address(email):
                pce = Project_client_email()
                pce.project = project[0]
                pce.email = email
                pce.name = name         # Kalle: name-field added
                pce.title = title       # Kalle: title-field added
                pce.save()
                
                request.user.message_set.create(message='Client e-mail added.')
            else:
                request.user.message_set.create(message='Please input a valid e-mail address.')
    
    return HttpResponseRedirect('/project/' + str(p_id) + '/edit/')

#-------------------------------------------------------------------------------
# 
#-------------------------------------------------------------------------------
def delete_client_email(request, p_id, e_id):
    if request.user.username == 'kth' or Project.objects.get(id=p_id).creator.id == request.user.id:
        Project_client_email.objects.filter(id=e_id).delete()
        request.user.message_set.create(message='E-mail client deleted.')

    return HttpResponseRedirect('/project/' + str(p_id) + '/edit/')
